//
//  RABookDetailController.m
//  ReadApp
//
//  Created by 飞猪 on 2018/11/7.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "RABookDetailController.h"
#import "RABookFaceModel.h"
#import "RDNetworkTool.h"

#import "RABookDetailTopCell.h"
#import "RABookDetailCenterCell.h"
#import "RABookDetailBottomCell.h"

#import "RAChapterListController.h"
#import "RABookDetailBottomView.h"
#import "AppDelegate.h"

@interface RABookDetailController () <
UITableViewDataSource,
UITableViewDelegate,
RABookDetailBottomViewDelegate,
KAAdBannerDelegate
>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *models;

@property (nonatomic, strong) RABookDetailBottomView *bookDetailBottomView;

@property (nonatomic, strong) UIView *adContainerView;
#pragma mark - 横幅广告
@property (nonatomic, strong) KAAdBanner *banner;

@end

@implementation RABookDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
  
  self.view.backgroundColor = self.tableView.backgroundColor;
  self.navigationItem.title = self.model.name;
  
  [self.view addSubview:self.tableView];
  [self.view addSubview:self.bookDetailBottomView];
  
  [self requestForDetail];
  
  [self addNoti];

  [self showBannerAdvert];
}

- (NSArray<RABookDetailModel *> *)getCacheData {
  
  return [RABookDetailModel zxg_selectAll];
  
}

- (void)addNoti {
//  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCacheData) name:RemoveNativeBookCacheNOti object:nil];
}

- (void)removeNoti {
//  [[NSNotificationCenter defaultCenter] removeObserver:self name:RemoveNativeBookCacheNOti object:nil];
}

- (void)viewWillLayoutSubviews {
  [super viewWillLayoutSubviews];
  
  CGRect rect = self.view.bounds;
  
  CGFloat marginB = 49;
  if ([self isiPhoneXScreen]) {
    marginB = 49 + 34;
  }
  self.tableView.frame = CGRectMake(0, 0, rect.size.width, rect.size.height - marginB);
  self.bookDetailBottomView.frame = CGRectMake(0, CGRectGetMaxY(self.tableView.frame), rect.size.width, 49);
  
}

- (void)dealloc {
  [self removeNoti];
}

#pragma mark - Network
- (void)requestForDetail {
  
  NSDictionary *params = @{
                           @"bookId": _model.toUrl ?: @""
                           };
  [SVProgressHUD showWithStatus:@"加载中..."];
  [SVProgressHUD setFont:[UIFont boldSystemFontOfSize:14.f]];
  [SVProgressHUD setForegroundColor:[UIColor grayColor]];
  [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
  [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
  [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
  
  [RDNetworkTool requestForBookDetail:params successBlock:^(RABookDetailModel *bookDetailModel) {
    [SVProgressHUD dismiss];
    
    if (bookDetailModel) {
      
      BOOL hiddenJoinBookBtn = NO;
      for (RABookDetailModel *tempM in [self getCacheData]) {
        BOOL res = [tempM.bookId isEqualToString:bookDetailModel.bookId];
        if (res) {
          hiddenJoinBookBtn = YES;
          break;
        }
      }
      
      if (hiddenJoinBookBtn) {
        [self.bookDetailBottomView setJoinBookHidden];
      }
      [self.models addObjectsFromArray:@[bookDetailModel, bookDetailModel, bookDetailModel, bookDetailModel]];
      [self.tableView reloadData];
      self.bookDetailBottomView.hidden = NO;
      
    }
    else {
      [SVProgressHUD showErrorWithStatus:@"暂无数据"];
    }
    
  } failBlock:^(NSString *errorMsg) {
    [SVProgressHUD dismiss];
    [SVProgressHUD showErrorWithStatus:errorMsg];
  }];
  
}

#pragma mark - Lazyload

- (UITableView *)tableView {
  if (!_tableView) {
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.backgroundColor = UIColorHex(ebebeb);
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 160.f;
    _tableView.tableFooterView = [UIView new];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  }
  return _tableView;
}


- (NSMutableArray *)models {
  if (!_models) {
    _models = [NSMutableArray array];
  }
  return _models;
}

- (RABookDetailBottomView *)bookDetailBottomView {
  if (!_bookDetailBottomView) {
    _bookDetailBottomView = [[RABookDetailBottomView alloc] init];
    _bookDetailBottomView.delegate = self;
    _bookDetailBottomView.hidden = YES;
  }
  return _bookDetailBottomView;
}

- (UIView *)adContainerView {
  if (!_adContainerView) {
    _adContainerView = [[UIView alloc] init];
    _adContainerView.backgroundColor = UIColorHex(ebebeb);
  }
  return _adContainerView;
}

#pragma mark - Event
- (void)beginRead:(RABookFaceModel *)model {
  
  RDReader *reader = [[RDReader alloc] init];
  
  RDConfiguration *config = [[RDConfiguration alloc] init];
  NSString *imgstr = [[NSUserDefaults standardUserDefaults] objectForKey:@"readerBGImage"];
  if (imgstr && ![imgstr isEqualToString:@"A39470"]) {
    UIColor *col = [UIColor colorWithHexString:imgstr];
    if (col) {
      config.readerBGImage = [UIImage imageWithColor:col];
    }
    else {
      config.readerBGImage = [UIImage imageNamed:@"yellow"];
    }
  }
  else {
    config.readerBGImage = [UIImage imageNamed:@"yellow"];
  }
  
  reader.config = config;
  
  RDReaderDelegateController *readerDelegateController = [RDReaderDelegateController new];
  [self addChildViewController:readerDelegateController];
  readerDelegateController.reader = reader;
  reader.delegate = readerDelegateController;
  
  [self presentViewController:reader animated:YES completion:nil];
  
  NSDictionary *params = @{
                              @"bookId" : model.toUrl ?: @"",
                              @"chId" : @"0"
                           };
  [reader beginWithParam:params];
  
}

// 横幅广告
- (void)showBannerAdvert {
    
  KAAdBanner *banner = [[KAAdBanner alloc] initWithSlot:@"QrmWalGe" withSize:KAAdBannerSize320x50 delegate:self currentController:self];
  self.banner = banner;
  [banner load];
  
}

#pragma mark - KAAdBannerDelegate
- (void)bannerAdCompleteLoadingWithAd:(nonnull KAAdBanner *)bannerAd {
  
  [self.adContainerView addSubview:bannerAd];
  [bannerAd setPosition:CGPointMake(kScreenWidth * 0.5, 50 * 0.5)];
  
}

- (void)bannerAdFailedLoadingForSlot:(nonnull NSString *)adSlot
                          withStatus:(nonnull NSError *)nativeAdStatus
                           andBanner:(nonnull KAAdBanner *)bannerAd {
  [bannerAd load];
}

- (void)bannerDidPresentScreen:(nonnull KAAdBanner *)bannerAd {
  
}

- (void)bannerDidDismissScreen:(nonnull KAAdBanner *)bannerAd {
  
}

#pragma mark - RABookDetailBottomViewDelegate
- (void)bookDetailBottomView:(RABookDetailBottomView *)view type:(RABookDetailBottomViewType)type {
  
  if (type == RABookDetailBottomViewTypeJoin) {
    
    RABookDetailModel *cacheModel = [self.models firstObject];
    BOOL archiverRes = [cacheModel zxg_insertOne];
    if (archiverRes) {
      [self.view makeToast:@"成功加入书架" duration:2.f position:[NSValue valueWithCGPoint:CGPointMake(kScreenWidth * 0.5, CGRectGetMinY(self.bookDetailBottomView.frame) - 46.f)]];
      [view setJoinBookHidden];
      
      [[NSNotificationCenter defaultCenter] postNotificationName:AddNativeBookCacheNOti object:nil];
    }
  }
  else {
    [self beginRead:_model];
  }
  
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return self.models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
  RABookDetailModel *model = self.models[indexPath.row];
  
  if (indexPath.row == 0) {
    RABookDetailTopCell *cell = [[RABookDetailTopCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    cell.model = model;
    return cell;
  }
  else if (indexPath.row == 1) {
    RABookDetailCenterCell *cell = [[RABookDetailCenterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    cell.model = model;
    [cell setMoreClick:^{
      model.isExpand = !model.isExpand;
      [tableView beginUpdates];
      [tableView reloadData];
//      [tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationAutomatic];
      [tableView endUpdates];
    }];
    return cell;
  }
  else if (indexPath.row == 2) {
    RABookDetailBottomCell *cell = [[RABookDetailBottomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RABookDetailAd"];
    [cell.contentView addSubview:self.adContainerView];
    self.adContainerView.frame = CGRectMake(0, 0, kScreenWidth, 50.f);
    return cell;
  }
  else {
    RABookDetailBottomCell *cell = [[RABookDetailBottomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
    cell.model = model;
    return cell;
  }

}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES];

  RABookDetailModel *model = self.models[indexPath.row];
  
  if (indexPath.row == self.models.count - 1) {
    
    RAChapterListController *chapterListController = [[RAChapterListController alloc] init];
    chapterListController.model = model;
    [self.navigationController pushViewController:chapterListController animated:YES];
    
  }
  
}

- (BOOL)isiPhoneXScreen {
  
  BOOL iPhoneX = NO;
  if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {//判断是否是手机
    return iPhoneX;
  }
  if (@available(iOS 11.0, *)) {
    UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
    if (mainWindow.safeAreaInsets.bottom > 0.0) {
      iPhoneX = YES;
    }
  }
  return iPhoneX;
  
}


@end
